import axios from 'axios'
import storage from '@/utils/storage'
import { showToast } from 'vant'

const service = axios.create({
  baseURL: '/',
  timeout: 30000
})

service.interceptors.request.use(
  async (config: any) => {
    if (!config.unAuth) {
      const token = storage.get('token')
      if (token) {
        config.headers['Authorization'] = `Bearer ${token}`
      } else {
        console.error(`'${config.name}: 'invalid token and auth required`)
        return
      }
    }
    return config
  },
  (error) => {
    Promise.reject(error)
  }
)

service.interceptors.response.use(
  async (response) => {
    return response.data
  },
  (error) => {
    if (error.response && error.response.status === 401) {
      storage.remove('token')
    } else if (error.response && error.response.data && error.response.data.message) {
      showToast(error.response.data.message)
    }
    return Promise.reject(error)
  }
)

export default service
